<?php
	//对需要的整数数据进行安全过滤 转换为标准的整型
	function _intval($int){
		return intval(trim($int));
	}
	//生成用于表单跟踪记录时星级评价和批注的异步唯一 
	function genHash(){
		return md5(microtime().rand(0,100000));
	}
	//生成用于Cloopen的用户的token 
	function geneToken(){
		return md5(microtime().rand(0,10000));
	}
	function strencode($string) {   
		   
		$string = base64_encode ( $string );   
		   
		$key = md5 ( 'inw2ld3tgs8' );   
		   
		$len = strlen ( $key );   
		   
		$code = '';   
		   
		for($i = 0; $i < strlen ( $string ); $i ++) {   
			   
			$k = $i % $len;   
			   
			$code .= $string [$i] ^ $key [$k];   
		   
		}        
		return base64_encode ( $code );   
	}
	/* 记录所有操作，并记录这些操作的日志成功与否的公用方法
	 * 参数 log_uid 用户uid （-1标示来自接口的调用日志）,
	 *  参数 log_uid用户uid,log_name 日志记录描述，log_status表示父记录的状态，1成功，0失败
	 *
	 */
	function logs($log_uid,$log_name,$log_type,$log_description = '',$log_status = 1){
		$LogsLog = M('LogsLog');
		$Logs = M('Logs');
		$data = array(
			'log_uid'	=> $log_uid,
			'log_name'	=> $log_name,
			'log_type'	=> $log_type,           //参数配置见数据表 sms_parameters
			'log_description'=> $log_description,
			'operate_status' => $log_status,    //操作失败的记录，还是操作成功的记录
			'create_time' => datetime()
		);
		$v = $Logs->add($data);
		if(!$v){
			$data = array(
				'log_uid'	=> $log_uid,
				'log_name'	=> $log_name.'记录失败',
				'log_type'	=> $log_type,           //参数配置见数据表 sms_parameters
				'log_description'=> $log_description,
				'log_status' => 0,    //操作失败的记录，还是操作成功的记录
				'create_time' => datetime()
			);
			$LogsLog->add($data);
		}
	}
	function loginLog(){
		$Agent = $_SERVER['HTTP_USER_AGENT'];
		$LoginLog = M('LoginLog');
		$LogsLog = M('LogsLog');
		$ip = get_client_ip();
		import('ORG.Net.IpLocation');// 导入IpLocation类
		$Ip = new IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件
		$area = $Ip->getlocation($ip); // 获取某个IP地址所在的位置
		
		//显示访问用户的浏览器信息
		//echo 'Browser: ' . determinebrowser($Agent) . '<BR>';
		//显示访问用户的操作系统平台
		//echo 'Platform: ' . determineplatform($Agent). '<BR>';
		$uid = session('uid');
		$data = array(
			'uid'	=> $uid,
			'ip'	=>$ip,
			'region'=>$area['area'],
			'country'=>$area['country'],
			'browser'=>determinebrowser($Agent),
			'os'	 =>determineplatform($Agent),
			'login_time'=>datetime(),
			'status' => session('login_status')?session('login_status'):0,    //1,正常登陆,0 失败
		);

		$v = $LoginLog->add($data);
		if($v){
			$result = array(
				'log_uid'  => $uid,
				'log_name' => $uid.'用户登陆记录成功',	
				'log_description' => '',
				'create_time' => datetime(),
				'status'	=> 1
			);
			$v = $LogsLog->add($result);
		}else{
			$result = array(
				'log_uid'  => $uid,
				'log_name' => $uid.'用户登陆记录失败',	
				'log_description' => '',
				'create_time' => datetime(),
				'status'	=> 0
			);
			$v = $LogsLog->add($result);
		}
		//if($v) return true;
		//else  return false
		
	}
	/** 
	 * 检查账号余额是否够用 2013-8-21 15:18:15
	 * @param   type    $varname    description
	 * @return  type    description
	 * @access  public or private
	 * @static  makes the class property accessible without needing an instantiation of the class
	 */
	function checkAssets($uid,$payoff)
	{
		$Assets = M('Assets');
		$assets = $Assets->where("uid = $uid")->find();
		if($assets){
			if(($assets['assets_total'] - $payoff ) > 0){
				return true;
			}else {
				return false;
			}
		}else{
			return false;
		}
	} // end func

	/**
	 * 加入流水账单，并更新个人资产
	 * @param   bigint    $order_id 消费订单或者充值订单ID
	 * @param   varchar   $type   consume or charge flag
	 * @param   float     $amount  交易金额
	 * @return  boolean   记录成功与否
	 * @access  public 
	 * @static 
	 */
	function __balance($uid,$order_id,$type,$amount){
		$Balance = M('Balance');
		$Assets = M('Assets');
		$chargeOrderId = 0;
		$consumeOrderId = 0;
		switch($type){
			case 'charge':
				$chargeOrderId = $order_id;
			    break;
			case 'consume':
			    $consumeOrderId = $order_id;
			    break;
			default:
			    $error = "the type is error";
			    break;
		}
		
		$balance = array(
					'uid' => $uid,
					'consume_order_id' => $consumeOrderId,
					'charge_order_id' => $chargeOrderId,
					'asset' => $amount,//交易额
					'type'	=> $type, //1:charge 0:consume
					'create_time' => datetime(),
					'update_time' => datetime(),
					'status' => 1
				); 
		$v = $Balance->add($balance);
		if($v){
			//更新个人资产表
			logs($uid,'添加到balance成功','',1);
			$as = $Assets->where("uid = $uid")->find();
			switch($type){
			case 'charge':
				$assets = $as['assets_total'] + $amount;
			    break;
			case 'consume':
			     $assets = $as['assets_total'] - $amount;
			    break;
			default:
			    $error = "你到底是充值，还是消费啊";
				logs($uid,'你到底是充值，还是消费啊',1,"amount :$amount",0);
				return false;
			    break;
			}
			$data = array(
				'uid'	=> $uid,
				'assets_total' => $assets,
				'update_time' => datetime()
			);
			//这里出错
			if($as){ 
				
				$v = $Assets->where("uid = $uid")->save($data);
				
			}else{
				$data['create_time'] = datetime();
				$data['update_time'] = '';
				$v = $Assets->add($data);
			}
			//echo $Assets->getLastSql();
			if($v){
				logs($uid,'更新个人资产表成功',1);
				return true;
			}else{
				logs($uid,'更新个人资产表失败',0);
				return false;
			}
			
		}else{
			logs($uid,'添加到balance失败',1);
			return false;
		}
	} // end func
	
	
	/**
	 * 生成消费订单
	 * @param   $uid 用户uid 
	 *          $type消费类型，sms发送短信 voice拨打电话 phone购买号码 其他以后再定 
	 *			$id 对应记录的ID
	 *          $unit单价，
	 *           $amount 总量
	 * @return  boolean or int (consume_order_id)
	 * @access  public
	 * @static 
	 */
	function __consumeOrder($uid,$type,$id,$unitPrice,$amount)
	{	
	    $ConsumeOrder = M('ConsumeOrder');			
		$total = $amount * $unitPrice;

		$consume = array(
					'owner_uid' => $uid,
					'amount' => $amount,
					'unit_price' => $unitPrice,
					'total' => $total,
					'create_time' => datetime(),
					'update_time' => datetime(),
					'remark' => '',
					'status' => 1
				);	
		switch($type){
			case 'sms':
				$consume['record_id'] = $id;
				$consume['type'] = $type;
			    $consume['remark'] = 'send sms';
			    break;
			case 'phone':
				$consume['purchase_record_id'] = $id;
				$consume['type'] = $type;
			    $consume['remark'] = 'purchase phone';
			    break;
			case 'voice':
				$consume['interview_id'] = $id;
				$consume['type'] = $type;
			    $consume['remark'] = 'voice call';    
			    break;
			default: 
				$error = "the type is error";
				break;
		}
		
		//记录到消费表
		$con = $ConsumeOrder->add($consume);
		if($con) return $con; //成功返回consume order id
		else return false;
		   
	} // end func
	/**
	 * 从parameters获取短信的单价
	 * @param   type    $varname    description
	 * @return  type    description
	 * @access  public or private
	 * @static  makes the class property accessible without needing an instantiation of the class
	 */
	function getSMSUnitPrice()
	{
	    $Parameters = M("Parameters");
		return $Parameters->where("name = 'sms_unit_price'")->getField('value');
		
	} // end func
	//2013-8-22 10:39:46
	function imgHtml($src,$html=""){
		foreach($src as $key=>$value){
			if(!in_array("emoticons",split("/",$value[0]))){
				$html = $html."<li><a class='fancybox-upload-img' href='".$value[0]."'><img class='upload' src='".$value[0]."'></a></li>";
			}
		}
		if($html == "") return "";
		return "<ul>".$html."</ul>";
	}
	//用于调试程序的方法(可随时删除)
	function message($msg){
		echo "<script>alert('".$msg."');</script>";
	}
?>